<template>
    <div class="media">
      <div class="eye-area">
        <div class="left">
          <h1 class="eye-title">左眼</h1>
          <video class="video" width="50%" height="auto" ref="left_video" autoplay :srcObject="left_videoSource">
            Video stream not available.
          </video>
          <canvas width="500" height="375" ref="left_canvas" id="left_canvas" />
          <img class="image" :src="left_photoSource" v-if="left_photoSource" />
          <div class="button-container">
            <button class="capture-button" @click="takePhoto('left')">确认拍照</button>
            <button class="capture-button" @click="retakePhoto('left')">重拍</button>
          </div>
        </div>
  
        <div class="right">
          <h1 class="eye-title">右眼</h1>
          <video class="video" width="50%" height="auto" ref="right_video" autoplay :srcObject="right_videoSource">
            Video stream not available.
          </video>
          <canvas width="500" height="375" ref="right_canvas" id="right_canvas" />
          <img class="image" width="50%" height="50%" :src="right_photoSource" v-if="right_photoSource" />
          <div class="button-container">
            <button class="capture-button" @click="takePhoto('right')">确认拍照</button>
            <button class="capture-button" @click="retakePhoto('right')">重拍</button>
          </div>
        </div>
      </div>
  
      <div class="button-container">
        <button class="capture-button" >自动对焦</button>
        <button class="capture-button" >开始诊断</button>
        <button class="capture-button" >自动对焦</button>
      </div>
  
      <div class="modal" @click="handleOutsideClick" v-if="isProcessing">
        <div class="modal-dialog" @click.stop>
          <div class="modal-content">
            <div class="modal-body">
              <p style="font-weight: bold; font-size:x-large;">请稍后在诊断结果中查看！</p>
            </div>
          </div>
        </div>
      </div>
    </div>
  </template>
  
  <script>
  import axios from 'axios';
  
  export default {
    data() {
      return {
        left_videoSource: null,
        right_videoSource: null,
        left_photoSource: null,
        right_photoSource: null,
        caseNo: localStorage.getItem("caseNo"),
        backendUrl: process.env.VUE_APP_BACKEND_URL || 'https://yzulcy.top/eye/diagnose',
        isProcessing: false,
        cameraName: 'USB2.0 Camera RGB', // 摄像头名称
        cameraDeviceId: null, // 摄像头 deviceId
      };
    },
  
    mounted() {
      this.$nextTick(() => {
        this.enumerateDevices().then(cameraId => {
          if (cameraId) {
            this.cameraDeviceId = cameraId;
            this.getCameraStream();
          } else {
            console.error(`没有找到名为 "${this.cameraName}" 的摄像头`);
          }
        });
      });
    },
  
    methods: {
      // 枚举媒体设备并查找特定摄像头
      async enumerateDevices() {
        const devices = await navigator.mediaDevices.enumerateDevices();
        const camera = devices.find(device => device.kind === 'videoinput' && device.label.includes(this.cameraName));
        console.log('Available devices:', devices);
        console.log('Available camera:', camera);
        this.cameraName = camera ? camera.label : ''; // 存储摄像头名称
        return camera ? camera.deviceId : null;
      },
  
      // 使用特定摄像头ID获取视频流
      getCameraStream() {
        const constraints = this.cameraDeviceId
          ? { video: { deviceId: { exact: this.cameraDeviceId } } }
          : { video: true };
  
        navigator.mediaDevices.getUserMedia(constraints)
          .then(stream => {
            const left_video = this.$refs.left_video;
            const right_video = this.$refs.right_video;
  
            if (left_video && right_video) {
              this.left_videoSource = stream;
              left_video.srcObject = stream;
              left_video.play();
  
              this.right_videoSource = stream;
              right_video.srcObject = stream;
              right_video.play();
            } else {
              console.error('Video elements not found.');
            }
          })
          .catch(error => console.error('Error accessing the camera:', error));
      },
  
      takePhoto(side) {
        if (!this.$refs[`${side}_canvas`] || !this.$refs[`${side}_video`]) {
          return;
        }
  
        const video = this.$refs[`${side}_video`];
        const canvas = this.$refs[`${side}_canvas`];
  
        const ctx = canvas.getContext('2d');
        ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
  
        this[`${side}_photoSource`] = canvas.toDataURL('image/png');
        console.log(this[`${side}_photoSource`]);
      },
  
      retakePhoto(side) {
        this[`${side}_photoSource`] = null;
      },
  
      async startDiagnosis() {
        try {
          this.isProcessing = true;
          if (!this.caseNo || this.caseNo.trim() === '') {
            throw new Error('病历号(caseNo)不能为空！');
          }
  
          const left_imageBlob = await this.dataUrlToBlob(this.left_photoSource);
          const right_imageBlob = await this.dataUrlToBlob(this.right_photoSource);
  
          const formData = new FormData();
          formData.append('left_file', left_imageBlob, `${this.caseNo}_left.png`);
          formData.append('right_file', right_imageBlob, `${this.caseNo}_right.png`);
          formData.append('caseNo', this.caseNo);
  
          const response = await axios.post(`${this.backendUrl}`, formData, {
            headers: { 'Content-Type': 'multipart/form-data' }
          });
  
          const result = response.data.data.data;
          localStorage.setItem('眼诊', result);
        } catch (error) {
          console.error('Error during diagnosis:', error);
          alert('诊断失败，请重试。');
        } finally {
          this.isProcessing = false;
        }
      },
  
      dataUrlToBlob(dataUrl) {
        return new Promise((resolve) => {
          const byteString = atob(dataUrl.split(',')[1]);
          const arrayBuffer = new ArrayBuffer(byteString.length);
          const uint8Array = new Uint8Array(arrayBuffer);
  
          for (let i = 0; i < byteString.length; i++) {
            uint8Array[i] = byteString.charCodeAt(i);
          }
  
          resolve(new Blob([arrayBuffer], { type: 'image/png' }));
        });
      },
  
      handleOutsideClick(event) {
        if (event.target === event.currentTarget) {
          this.isProcessing = false;
        }
      },
    },
  };
  </script>
  
  
  <style scoped>
  #app {
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
    display: flex;
    flex-direction: column;
    gap: 1rem;
  }
  
  .eye-title {
    text-align: center;
    font-family: '华文楷体', '楷体', 'Arial', sans-serif; /* 使用更优雅的中文字体 */
    font-size: 1.5em; /* 调整字体大小 */
    color: #444; /* 更深一些的文字颜色 */
    letter-spacing: 2px; /* 增加字母间距 */
    line-height: 1; /* 行高 */
    margin-bottom: 5px; /* 底部边距 */
  }
  /* 定义媒体容器样式 */
  .media {
    display: flex;
    flex-direction: column;
    gap: 1rem;
  }
  
  .eye-area {
    display: flex;
    flex-direction: row;
  }
  
  .left,
  .right {
    flex: 1;
    /* 让每个子元素占据一半的空间 */
    position: relative;
    /* 使图片位置相对于视频 */
  }
  
  .video {
    width: 97%;
    /* 视频占据父元素的全部宽度 */
    height: auto;
    border-radius: 8px;
    overflow: hidden;
    background-image: url('@/assets/image/图片预览.png');
    background-size: cover;
    background-position: center;
    border: 2px solid #d3d2d2;
  }
  
  .image {
    position: absolute;
    /* 绝对定位 */
    top: 0;
    left: 0;
    width: 98%;
    /* 图片宽度与视频相同 */
    height: 88%;
    object-fit: cover;
    /* 保持图片原始比例的同时填充整个容器 */
    border-radius: 8px;
  }
  
  /* 视频区域的最大宽度 */
  /* .video-area {
    max-width: 95%;
    position: relative;
  } */
  
  
  /* 按钮容器 */
  .button-container {
    display: flex;
    justify-content: center;
    align-items: center;
  }
  
  /* 拍摄按钮样式 */
  .capture-button {
    padding: 10px 20px;
    background-color: #007BFF;
    color: white;
    font-size: larger;
    font-weight: bold;
    border: none;
    border-radius: 5px;
    cursor: pointer;
    transition: background-color 0.1s ease;
    margin: 2%;
  }
  
  /* 悬停时改变按钮背景颜色 */
  .capture-button:hover {
    background-color: #e1475e;
  }
  
  /* 隐藏canvas元素 */
  #left_canvas {
    display: none;
  }
  
  /* 隐藏canvas元素 */
  #right_canvas {
    display: none;
  }
  
  /* 模态框样式 */
  .modal {
    position: fixed;
    z-index: 1000;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    overflow: auto;
    background-color: rgba(0, 0, 0, 0.5);
  }
  
  .modal-dialog {
    background-color: #fff;
    margin: 15% auto;
    padding: 20px;
    border-radius: 5px;
    width: 30%;
    text-align: center;
  }
  
  .modal-body p {
    font-size: 16px;
    color: #333;
  }
  
  .eye-area>div {
    flex: 1;
    display: inline-block;
    vertical-align: top;
    margin-right: 1rem;
  }
  
  @media (max-width: 600px) {
    .eye-area>div {
      margin-bottom: 1rem;
      margin-right: 0;
    }
  }
  </style>